package com.example.demo.controller;

import com.aspose.slides.ISlide;
import com.aspose.slides.License;
import com.aspose.slides.Presentation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
/**
 * @author: yby
 * @desc:
 * @date: 2024/9/20 10:18
 */
@RestController
@RequestMapping("/api")
public class PptController {


    private static InputStream license;
/**
 * 获取license
 *
 * @return
 */
public static boolean getLicense() {

    boolean result = false;
    license = PptController.class.getClassLoader().getResourceAsStream("license.xml");
    if (license != null) {
        License aposeLic = new License();
        aposeLic.setLicense(license);
        result = true;
    }
    return result;
}

/**
 * 转Image
 *
 * @return
 */
@GetMapping("/convertImage")
public String convertImage() {
    long startTime = System.currentTimeMillis();
    String time = "";
    // 验证License
    if (!getLicense()) {
        return "验证License失败";
    }
    String fileName = "D:\\资料\\个人工作\\辅助资料\\22.ppt";
    String dest = "D:\\资料\\个人工作\\辅助资料\\";
    File file = new File(fileName);
    if (!file.exists()) {
        return "转换文件不存在";
    }
    String filePath = file.getParent()+File.separator;
    //String dest = filePath + getFileNameNoEx(file.getName())+"_JPG";
    File destPath = new File(dest);
    if (!destPath.exists()) {
        destPath.mkdir();
    }
    try {
        FileInputStream fileInput = new FileInputStream(fileName);
        Presentation pres = new Presentation(fileInput);
        int i;
        for (i = 0; i < pres.getSlides().size(); i++) {
            ISlide slide = pres.getSlides().get_Item(i);
            int height = (int)(pres.getSlideSize().getSize().getHeight()-150);
            int width = (int)(pres.getSlideSize().getSize().getWidth()-150);
            BufferedImage image = slide.getThumbnail(new java.awt.Dimension(width, height));
            //每一页输出一张图片
            File outImage = new File(dest+ File.separator + (i+1) + ".JPG");
            ImageIO.write(image, "JPG", outImage);
        }
        long endTime = System.currentTimeMillis();
        time = ((endTime-startTime)/1000) + "s";
    } catch (Exception e) {
        return e.getMessage();
    }
    return "转换成功 耗时："+time;
}
/**
 * 获取文件名，去除扩展名的
 *
 * @param filename
 * @return
 */
private String getFileNameNoEx(String filename) {
    if ((filename != null) && (filename.length() > 0)) {
        int dot = filename.lastIndexOf('.');
        if ((dot > -1) && (dot < (filename.length()))) {
            return filename.substring(0, dot);
        }
    }
    return filename;
}

}
